package com.zmx.patientend.view.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.R;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;
import com.zmx.patientend.view.util.TimeCount;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ModifyPhoneNumberActivity extends BaseActivity {

    @BindView(R.id.reg_account)
    EditText regAccount;
    @BindView(R.id.reg_code_edt)
    EditText regCodeEdt;
    @BindView(R.id.reg_code_button)
    TextView regCodeButton;
    @BindView(R.id.phone_number)
    TextView phone_number;
    @BindView(R.id.submit)
    Button submit;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_modify_phone_number;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
        phone_number.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.mobile,""));
        setToolbar(R.id.tool_bar);
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:
                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        Toast(jsonObject.getString("msg"));
                        if (jsonObject.getInt("code" ) == 1){

                            TimeCount timeCount = new TimeCount(regCodeButton, 60000, 1000);
                            timeCount.start();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case 2:
                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        Toast(jsonObject.getString("msg"));
                        if (jsonObject.getInt("code" ) == 1){

                            MySharedPreferences.getInstance(mActivity).saveKeyObjValue(MySharedPreferences.mobile,regAccount.getText().toString().trim());
                            phone_number.setText(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.mobile,""));
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
            }

        }
    };


    public void getCode() {

        List<String> ls = new ArrayList<>();
        ls.add(regAccount.getText().toString());
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getMobileChange");
        params.put("data[mobile]", regAccount.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.member/entry", params, handler, 1, 404);


    }
    public void mobileSet() {

        List<String> ls = new ArrayList<>();
        ls.add(regCodeEdt.getText().toString());
        ls.add(regAccount.getText().toString());
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "mobileSet");
        params.put("data[mobile]", regAccount.getText().toString());
        params.put("data[code]", regCodeEdt.getText().toString());
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.member/entry", params, handler, 2, 404);


    }


    @OnClick({R.id.reg_code_button, R.id.submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {

            case R.id.reg_code_button:

                //判断用户输入是否为空
                if (getAccount().isEmpty()) {
                    Toast("你输入的账号为空！");
                    return;
                }
                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                getCode();

                break;
            case R.id.submit:

                //判断用户输入是否为空
                if (getAccount().isEmpty()) {
                    Toast("你输入的账号为空！");
                    return;
                }


                if (!isChinaPhoneLegal(getAccount())) {
                    Toast("输入正确的手机号码！");
                    return;
                }

                if (regCodeEdt.getText().toString().isEmpty()) {
                    Toast("验证码不能为空！");
                    return;
                }
                mobileSet();
                break;
        }
    }

    /**
     * 获取手机号
     */
    public String getAccount() {
        return regAccount.getText().toString().trim();//去掉空格
    }
    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 145,147,149
     * 15+除4的任意数(不要写^4，这样的话字母也会被认为是正确的)
     * 166
     * 17+3,5,6,7,8
     * 18+任意数
     * 198,199
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        // ^ 匹配输入字符串开始的位置
        // \d 匹配一个或多个数字，其中 \ 要转义，所以是 \\d
        // $ 匹配输入字符串结尾的位置
        String regExp = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[3,5,6,7,8])" +
                "|(18[0-9])|(19[8,9]))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


}
